﻿using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace example
{
    /// <summary>
    /// 演示创建自定义控件
    /// </summary>
    public class Example3Window : EditorWindow
    {
        [MenuItem("Window/Examples/Example_3")]
        static void OpenExample()
        {
            GetWindow<Example3Window>().Show();
        }

        private void OnEnable()
        {
            this.rootVisualElement.Add(Resources.Load<VisualTreeAsset>("Uxmls/custom_control").CloneTree());
        }
    }
}

public class ImageSlider : VisualElement
{
    public class Traits : UxmlTraits
    {
        UxmlFloatAttributeDescription m_Min = new UxmlFloatAttributeDescription
        {
            name = "min",
            defaultValue = 0.5f,
        };
        UxmlFloatAttributeDescription m_Max = new UxmlFloatAttributeDescription
        {
            name = "max",
            defaultValue = 2f,
        };
        UxmlFloatAttributeDescription m_Size = new UxmlFloatAttributeDescription
        {
            name = "size",
            defaultValue = 100f,
        };

        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
        {
            base.Init(ve, bag, cc);

            var target = (ImageSlider)(ve);
            target.min = m_Min.GetValueFromBag(bag, cc);
            target.max = m_Max.GetValueFromBag(bag, cc);
            target.mSize = m_Size.GetValueFromBag(bag, cc);
        }
    }
    public class Factory : UxmlFactory<ImageSlider, Traits> { }
    public Slider mSlider;
    public Image mImage;

    public float min
    {
        get { return mSlider.lowValue; }
        set
        {
            mSlider.lowValue = value;
        }
    }

    public float max
    {
        get { return mSlider.highValue; }
        set
        {
            mSlider.highValue = value;
        }
    }

    private float mSize = 100f;

    public ImageSlider()
    {
        mSlider = new Slider();

        mSlider.style.width = 100;

        mImage = new Image();

        mImage.style.width = mImage.style.height = mSize;

        this.style.justifyContent = Justify.Center;
        this.style.alignItems = Align.Center;

        this.Add(mSlider);
        this.Add(mImage);

        mImage.image = Resources.Load<Texture2D>("Images/doge");

        mSlider.RegisterValueChangedCallback(evt =>
        {
            mImage.style.width = mImage.style.height = mSize * evt.newValue;
        });
    }
}